from django.http import StreamingHttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
import json

@method_decorator(csrf_exempt, name='dispatch')
class MutChatAPIView(View):
    def post(self, request):
        try:
            # 解析JSON请求体
            data = json.loads(request.body)
            
            # 获取消息列表
            messages = data.get('messages', [])
            
            # 验证消息格式
            if not messages or not isinstance(messages, list):
                return StreamingHttpResponse('data: {"error": "Invalid messages format"}\n\n', 
                                           content_type='text/event-stream')
            
            # 获取用户消息内容
            user_message = ""
            for message in messages:
                if message.get('role') == 'user':
                    user_message = message.get('content', '')
                    break
            
            # 直接返回用户消息作为响应
            response_text = user_message
            
            # 流式响应的生成器函数
            def stream_response():
                # 初始响应
                full_content = ""
                
                # 直接发送完整响应
                data = {
                    "type": "content",
                    "content": response_text,
                    "full_content": response_text
                }
                yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
                
                # 发送结束信号
                end_data = {"type": "end", "full_content": response_text}
                yield f"data: {json.dumps(end_data, ensure_ascii=False)}\n\n"
            
            # 创建流式响应
            response = StreamingHttpResponse(
                stream_response(),
                content_type='text/event-stream'
            )
            
            # 设置响应头
            response['Cache-Control'] = 'no-cache'
            response['Connection'] = 'keep-alive'
            response['Access-Control-Allow-Origin'] = '*'
            response['Access-Control-Allow-Headers'] = 'Content-Type'
            response['Access-Control-Allow-Methods'] = 'POST, OPTIONS'
            
            return response
            
        except json.JSONDecodeError:
            return StreamingHttpResponse('data: {"error": "Invalid JSON format"}\n\n', 
                                       content_type='text/event-stream')
        except Exception as e:
            return StreamingHttpResponse(f'data: {{"error": "{str(e)}"}}\n\n', 
                                       content_type='text/event-stream')